import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from '../entities/user.entity';
import { Code } from '../entities/code.entity';
import { Token } from '../entities/token.entity';
import { Repository } from 'typeorm';
import utils from '../utils';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
    @InjectRepository(Code)
    private readonly codeRepository: Repository<Code>,
    @InjectRepository(Token)
    private readonly tokenRepository: Repository<Token>,
  ) {}

  async findOneByToken(token: string) {
    let tokenRet = await this.tokenRepository.findOne({ token: token });

    if (utils.isExpired(tokenRet.expireTime, tokenRet.createTime)) {
      tokenRet = undefined;
    }

    let userRet = null;

    if (!!tokenRet) {
      userRet = await this.userRepository.findOne({ id: tokenRet.pid });
    }

    return userRet;
  }
}
